package PrjDBConf

import (
	"dgo/goutils/utils"
	"gitee.com/ymofen/supervalue"
)

type ConfLocal struct {
	config_home string
}

func NewLocalAppConf(config_home string) *ConfLocal {
	rval := &ConfLocal{
		config_home: config_home,
	}
	return rval
}

func (this *ConfLocal) CheckEnv() error {
	if len(this.config_home) == 0 {
		this.config_home = utils.GetExecuteFileDirectory() + utils.PathSeparator + "localconf" + utils.PathSeparator
	}
	utils.ForceCreatePath(this.config_home)
	return nil

}

func (this *ConfLocal) GetConfByID(strID, strTypeID string) (error, []byte) {
	// 0 不新建, 1: 新建(如果appid对应不存在), 10: 新建Type(如果不存在则新建)
	fileName := this.config_home + strTypeID + utils.PathSeparator + strID

	if utils.FileIsExists(fileName) {
		buf, err := utils.ReadFile(fileName)
		return err, buf
	} else {
		return nil, nil
	}
}

func (this *ConfLocal) ConfUpdate(appid, typeid, conf string) error {
	fileName := this.config_home + typeid + utils.PathSeparator + appid
	err := utils.ForceCreateFilePath(fileName)
	if err != nil {
		return err
	}
	err = utils.RewriteFile(fileName, []byte(conf))
	if err != nil {
		return err
	}
	if ConfUpdateCallBack != nil {
		ConfUpdateCallBack(appid, typeid, conf)
	}
	return nil
}

/*
**

	如果是JSON则返回supervalue
	否则返回ByteBuilder
*/
func (this *ConfLocal) GetConf(strAppID, strTypeID, strConfAsType string, newFlag int) (error, interface{}) {
	// 0 不新建, 1: 新建(如果appid对应不存在), 10: 新建Type(如果不存在则新建)
	fileName := this.config_home + strTypeID + utils.PathSeparator + strAppID

	var txtB utils.BytesBuilder

	// appid 对应的标记
	exists_flag_1 := utils.FileIsExists(fileName)

	if newFlag == 1 && !exists_flag_1 {
		utils.ForceCreateFilePath(fileName)
		if strConfAsType == "json" {
			utils.RewriteFile(fileName, []byte("{}"))
		} else {
			utils.RewriteFile(fileName, []byte("# 请进行配置"))
		}
	}

	if !exists_flag_1 {
		return nil, nil
	}

	if strConfAsType == "json" {
		respConf, err := wrapper.NewSVFromFile(fileName)
		return err, respConf
	} else {
		buf, err := utils.ReadFile(fileName)
		txtB.Write(buf)
		return err, txtB
	}
}
